package com.zookeeper.curator;

import com.zookeeper.utils.ConnectionUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author 咕唧
 * @Date 2022/7/2 18:03
 * @Version 1.0
 */
public class CuratorBase {

    public static void main(String[] args) throws Exception {
//        createPath();
//        createPathWithParent();
//        testGet();
//        testSet();
//        testGetChildren();
        testDelete();
    }

    /**
     * 获取子节点子节点
     *
     * @throws Exception
     */
    public static void testGetChildren() throws Exception {
        CuratorFramework framework = ConnectionUtil.getFramework();
        List<String> list = framework.getChildren().forPath("/test");
        list.forEach(System.err::println);
    }

    public static void testDelete() throws Exception {
        CuratorFramework framework = ConnectionUtil.getFramework();
        Void test = framework.delete()
                //如果存在子节点，先删除子节点
                .deletingChildrenIfNeeded()
                .forPath("/test");
        System.err.println(test);
    }

    public static void testSet() throws Exception {
        CuratorFramework framework = ConnectionUtil.getFramework();
        Stat stat = framework.setData().forPath("/test");
        System.err.println(stat);
    }

    public static void testGet() throws Exception {
        CuratorFramework framework = ConnectionUtil.getFramework();
        byte[] bytes = framework.getData().forPath("/test");
        System.err.println(new String(bytes));
    }

    /**
     * 如果父节点不存在，则创建父节点
     *
     * @throws Exception
     */
    private static void createPathWithParent() throws Exception {
        CuratorFramework framework = ConnectionUtil.getFramework();
        framework.create()
                //如果父节点不存，则创建父节点，在继续创建
                .creatingParentsIfNeeded()
                //创建一个持久化节点
                .withMode(CreateMode.PERSISTENT)
                //指定要操作的路径，这个方法需要最后调用
                .forPath("/a/b/c/d", "hahadeshuju".getBytes(StandardCharsets.UTF_8));
    }

    private static void createPath() throws Exception {
        CuratorFramework framework = ConnectionUtil.getFramework();
        framework.create()
                //创建一个持久化节点
                .withMode(CreateMode.PERSISTENT)
                //指定要操作的路径，这个方法需要最后调用
                .forPath("/haha", "hahadeshuju".getBytes(StandardCharsets.UTF_8));
    }
}
